<?php

class Damages_Tasks {

  public static function resetPassword($ids = null, $silent = false) {
    $em = new Damages_Emails($silent);
    $q = DamagesUsersQuery::create();
    if ($ids)
      $q->filterById($ids);
    $users = $q->find();
    foreach ($users as $user) {
      $newPass = self::generatePassword();
      $user->setPassword(Damages_AuthData_Email::crypt($newPass));
      $user->setForcePasswordChange(1);
      $em->sendNewPasswordNotification($user, $newPass);
      $user->save();
    }
  }

  public static function resetBrandPassword($code) {
    $em = new Damages_Emails();
    $q = DamagesUsersQuery::create()
            ->filterByPassword(0)
            ->useUserDealersQuery()
            ->useDealersQuery()
            ->useDictBrandsQuery()
            ->filterByCode($code)
            ->endUse()
            ->endUse()
            ->endUse();

    $users = $q->find();
    foreach ($users as $user) {
      $newPass = self::generatePassword();
      $user->setPassword(Damages_AuthData_Email::crypt($newPass));
      $user->setForcePasswordChange(1);
      $em->sendNewPasswordNotification($user, $newPass);
      $user->save();
    }
  }

  public static function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $count = mb_strlen($chars);

    for ($i = 0, $result = ''; $i < $length; $i++) {
      $index = rand(0, $count - 1);
      $result .= mb_substr($chars, $index, 1);
    }
    return $result;
  }

}

?>